import pickle
import struct
import traceback

class Config:
    VERSION = None
    PATH    = None

    def save(self, path=None):
        if path is None:
            assert self.PATH
            path = self.PATH

        assert self.VERSION

        try:
            data = pickle.dumps(self)
            with open(path, "wb") as f:
                f.write(struct.pack("<ii", self.VERSION, len(data)))
                f.write(data)

            return True
        except:
            traceback.print_exc()
            return False

    @classmethod
    def load(cls, path=None):
        if path is None:
            assert cls.PATH
            path = cls.PATH

        assert cls.VERSION

        try:
            with open(path, "rb") as f:
                version = f.read(8)
                version, size = struct.unpack("<ii", version)
                if version != cls.VERSION:
                    return cls()

                data = f.read(size)
                return pickle.loads(data)
        except IOError:
            return cls()
